package com.zan.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

/**
 * @Author Zan
 * @Date 2023/10/17 12:39
 * @Description : JWT工具类
 */
public class JwtUtils {

    // 有效期
    public static final Long JWT_TTL = 60 * 60 * 1000L; // 60 * 60 * 1000 一个小时

    //设置密钥明文
    public static final String JWT_KEY = "Zan";

    public static String getUUID() {
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        return token;
    }

    /**
     * 生成jwt
     * @param subject token中要存放的数据（json格式）
     * @return
     */
    public static String createJWT(String subject) {
        JwtBuilder builder = getJwtBuilder(subject, null, getUUID());
        return builder.compact();
    }

    /**
     * 生成jwt
     * @param subject token中要存放的数据（json格式）
     * @param ttlMillis token超时时间
     * @return
     */
    public static String createJWT(String subject, Long ttlMillis) {
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, getUUID());
        return builder.compact();
    }

    /**
     * 生成jwt(即token)
     * @param id
     * @param subject
     * @param ttlMillis
     * @return
     */
    public static String createJWT(String id, String subject, Long ttlMillis) {
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, id);
        return builder.compact();
    }

    private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        SecretKey secretKey = generalKey();
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        if (ttlMillis == null) {
            ttlMillis = JwtUtils.JWT_TTL;
        }
        long expMillis = nowMillis + ttlMillis;
        Date expDate = new Date(expMillis);
        return Jwts.builder()
                .setId(uuid)    //唯一的ID
                .setSubject(subject)  //主题，可以是JSON数据
                .setIssuer("Zan") //签发者
                .setIssuedAt(now) //签发时间
                .signWith(signatureAlgorithm, secretKey) //使用HS256对称加密算法签名，第二个参数给加密的密钥
                .setExpiration(expDate); //过期时间
    }

    public static SecretKey generalKey() {
        byte[] encodedKey = Base64.getDecoder().decode(JWT_KEY);
        SecretKeySpec key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }

    /**
     * 解析jwt
     * @param jwt
     * @return
     */
    public static Claims parseJWT(String jwt) {
        SecretKey secretKey = generalKey();
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }

    public static void main(String[] args) {
        // 123
//        String jwt = createJWT("123");
//        System.out.println(jwt);
        Claims claims = parseJWT("eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxMDY3ZDFmYjE0OGY0Y2NiYTIxZmVhOTc2NjRlYjI5OCIsInN1YiI6IjEiLCJpc3MiOiJaYW4iLCJpYXQiOjE2OTc1MjY1MTEsImV4cCI6MTY5NzUzMDExMX0.mte47zIlX3r-pz9J_wCz6X0N66yr7zcWRTIKOA4Q2eI");
        System.out.println(claims);
    }
}
